package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */

@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private SeckillVoucherServiceImpl seckillVoucherService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result secKill(Long voucherId) {
        //1.查询优惠劵信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2.判断秒杀是否开始（now在开始时间之后，在结束时间之前）
        if (LocalDateTime.now().isBefore(voucher.getBeginTime())) {
            //3.未开始：返回”秒杀活动还未开始!“
            Result.fail("秒杀活动还未开始!");
        }
        if (LocalDateTime.now().isAfter(voucher.getEndTime())) {
            Result.fail("秒杀活动已结束!");
        }
        //4.秒杀开始：判断库存是否充足
        if (voucher.getStock() < 1) {
            //5.库存不充足：返回”库存不充足！“
            Result.fail("优惠卷已经被抢完了，下次早点来!");
        }
        UserDTO user = UserHolder.getUser();
        Long id = user.getId();
//        synchronized (id.toString().intern()) {           //用JVM内自带的悲观锁
        //创建锁的对象
        SimpleRedisLock lock = new SimpleRedisLock("order:" + id, stringRedisTemplate);
        //尝试获取锁
        boolean success = lock.tryLock(1200L);
        if (!success) {
            return Result.fail("每个用户只能购买一张优惠劵！");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            lock.unLock();
        }
//        }
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {

        UserDTO user = UserHolder.getUser();
        Long id = user.getId();
        //5.一人一单功能：根据优惠劵id和用户id判断是否用户已经购买过
        int count = query().eq("user_id", id).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("每个用户只能购买一单哦！");
        }


        //6.库存充足：扣减库存，创建订单
        boolean success = seckillVoucherService.update().setSql("stock= stock - 1")
                .eq("voucher_id ", voucherId).gt("stock", 0).update();

        if (!success) {
            return Result.fail("库存不足");
        }
        VoucherOrder voucherOrder = new VoucherOrder();
        long order = redisIdWorker.nextId("order");
        voucherOrder.setId(order);

        voucherOrder.setUserId(user.getId());
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        //7.返回订单ID
        return Result.ok(order);

    }
}
